<template>
  <view style="width: 100%;position: relative;display: block;">
    <scroll-view :show-scrollbar="false" class="fox-scroll-pager" scroll-x :scroll-left="scrollLeftVal"
                 scroll-with-animation @scroll="onScroll" @touchend="gridlistTouchend"
    >
      <view class="fox-scroll-pager-warpper">
        <slot></slot> <!-- 插槽用于插入外部内容 -->
      </view>
    </scroll-view>
    <!-- 面板指示器 -->
    <view v-if="indicator" class="fox-scroll-indicator" :style="{ bottom: indicatorPosition }">
      <view v-for="(item, index) in totalPages" :key="index" class="fox-scroll-indicator-item"
            :style="indicatorStyle(index)"
      />
    </view>

    <view v-if="showoverlay" class="fox-scrollview-overlay" />
  </view>
</template>

<script>
export default {
  name: 'FoxScrollPager',
  props: {
    initialScrollLeft: {
      type: Number,
      default: 0,
    },
    indicator: { // 控制是否显示面板指示器
      type: Boolean,
      default: true,
    },
    indicatorColor: { // 指示器非激活颜色
      type: String,
      default: '#999',
    },
    indicatorActiveColor: { // 指示器激活颜色
      type: String,
      default: '#2AA4F4',
    },
    indicatorPosition: {
      type: String,
      default: '10px', // 默认距离底部的距离
    },
  },
  data() {
    return {
      scrollLeftVal: 0, // 当前滚动位置
      currentPageIndexVal: 0, // 当前页索引
      lastScrollLeft: 0, // 上一次的滚动位置，用于判断滑动方向
      contentWidthVal: 0, // 内容总宽度
      totalPages: 0, // 总页数

      temporarilyLeftVal: 0,

      showoverlay: false,

    }
  },
  watch: {
    // 监听 initialScrollLeft prop 变化，更新 scrollLeftVal
    initialScrollLeft(newVal) {
      this.scrollLeftVal = newVal
    },
    contentWidthVal() {
      this.calculateTotalPages()
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.scrollLeftVal = 1
    })
  },
  methods: {
    // 根据滚动位置和方向计算页面索引
    calculatePageIndex(scrollLeft, offsetWidth) {
      const fullPagesScrolled = Math.floor(scrollLeft / offsetWidth)
      const remainingOffset = scrollLeft % offsetWidth

      // 判断滑动方向
      const isScrollingForward = scrollLeft > this.lastScrollLeft
      this.lastScrollLeft = scrollLeft

      if (isScrollingForward && remainingOffset >= offsetWidth * 0.6) {
        return fullPagesScrolled + 1
      }
      else if (!isScrollingForward && remainingOffset <= offsetWidth * 0.4) {
        return fullPagesScrolled
      }
      else {
        return fullPagesScrolled
      }
    },
    // 获取scroll宽度
    getWindow() {
      return new Promise((resolve, reject) => {
        const info = uni.createSelectorQuery().in(this).select('.fox-scroll-pager')
        info.boundingClientRect((data) => {
          if (data) {
            resolve(data) // 返回获取到的位置信息
          }
          else {
            reject('') // 如果没有获取到数据，可以返回错误
          }
        }).exec()
      })
    },
    async getWinWidth() {
      const winData = await this.getWindow()
      return winData.width || 0
    },

    // 计算总页数
    async calculateTotalPages() {
      const offsetWidth = await this.getWinWidth()
      const contentWidth = this.contentWidthVal
      this.totalPages = Math.ceil(contentWidth / offsetWidth)
    },

    // 滚动事件处理
    async onScroll(e) {
      const {
        scrollLeft,
        scrollWidth
      } = e.detail
      this.contentWidthVal = scrollWidth
      // 输出调试信息
      // console.log('scrollLeft during scroll:', scrollLeft);
      // console.log('scrollWidth:', scrollWidth);

      // 写这里会影响性能，但是目前实现功能最重要
      // this.calculateTotalPages(); // 计算总页数
      this.temporarilyLeftVal = scrollLeft

      this.$emit('update:scrollLeft', scrollLeft) // 触发滚动位置更新
    },

    // 触摸结束事件，滚动至最近页面位置
    async gridlistTouchend(e) {
      // console.log('触发了1')
      // 计算当前页面索引
      const pageIndex = this.calculatePageIndex(this.temporarilyLeftVal, await this.getWinWidth())
      // console.log('计算pageindex2');
      this.scrollLeftVal = this.temporarilyLeftVal
      // console.log('赋值scrollLeftVal3')
      // console.log('pageIndex:', pageIndex);
      // console.log('currentPageIndexVal:', this.currentPageIndexVal);

      this.$nextTick(async () => {
        // 重新计算scrollLeft（确保滑动结束时滚动位置是最新的）
        const offsetWidth = await this.getWinWidth()
        // console.log('计算组件宽度offsetWidth4')
        if (pageIndex !== this.currentPageIndexVal) {
          this.currentPageIndexVal = pageIndex
          this.$emit('update:currentPageIndex', pageIndex) // 更新当前页码
          // console.log('数据有变化，更新最新页5')
        }
        else {
          // console.log('数据无变化，不更新页数5')
        }

        this.scrollLeftVal = this.currentPageIndexVal * offsetWidth
        // console.log('赋值新页的scrolLeft的值6',this.temporarilyLeftVal)

        // console.log('scrollLeftVal after update:', this.scrollLeftVal);
        this.showoverlay = true
        setTimeout(() => {
          this.showoverlay = false
        }, 900)
      })
    },

    // 指示器的样式
    indicatorStyle(index) {
      return {
        backgroundColor: index === this.currentPageIndexVal ? this.indicatorActiveColor : this.indicatorColor,
      }
    },
  }
}
</script>

<style scoped>
 .fox-scrollview-overlay {
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, .0);
  top: 0;
  left: 0;
 }

 .fox-scroll-pager {
  /* 在此处添加样式 */
  width: 100%;
  white-space: nowrap;
 }

 .fox-scroll-pager-warpper {
  display: flex;
  width: 100%;
  padding-bottom: 10rpx;
 }

 .fox-scroll-indicator {
  /* position: absolute; */
  width: 100%;
  display: flex;
  justify-content: center;
  z-index: 999;
  margin-top: 2rpx;
 }

 .fox-scroll-indicator-item {
  /* width: 8px;
  height: 8px;
  border-radius: 50%; */
  width: 20rpx;
  height: 6rpx;
  /* border-radius: 50%; */
  margin: 0 5rpx;
  background-color: #999;
  /* 默认颜色 */
 }
</style>
